package me.feng.servlet

import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletRequest
import me.feng.domain.Member
import java.sql.Timestamp
import java.util.Date
import me.feng.entity.User
import me.feng.entity.Message
import me.feng.entity.Event
import me.feng.entity.MessageType
import me.feng.actors.MainActor
import me.feng.entity.EventType
import com.lambdaworks.jacks.JacksMapper
import javax.servlet.http.Cookie
import javax.servlet.annotation.WebServlet


@WebServlet(Array("/authosc.do"))
class OscauthServlet extends HttpServlet {

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) {
    val uid = req.getParameter("uid")
    var member = Member.getMemberbyUid(uid)
    if (member == null) {
      // osc 帐号已存在
      val name = req.getParameter("name")
      val portrait = req.getParameter("portrait")
      val username = req.getParameter("username")
      val m = new Member(uid, name, uid, uid, new Timestamp(new Date().getTime()), portrait, "")
      member = Member.save(m)
    }
    val msg = new Message(MessageType.EVENT, new Event(User.member2User(member), MainActor.DEFAULT_MAIN_ID, EventType.LOGIN_SUCCESS))

    val result = JacksMapper.writeValueAsString(msg)
    val c = new Cookie("sid", req.getSession().getId())
    c.setPath("/")
    resp.addCookie(c)
    resp.setCharacterEncoding("UTF-8")
    resp.setContentType("application/x-javascript;charset=UTF-8");
    val out = resp.getWriter()
    out.print(result)
    out.close()
  }

  override def doPost(req: HttpServletRequest, resp: HttpServletResponse) {
    doGet(req, resp);
  }
}